//
//  BaseRequestModel.m
//  LittleRed
//
//  Created by cnp on 17/3/29.
//  Copyright © 2017年 xinmiao. All rights reserved.
//

#import "BaseRequestModel.h"
#import <MBProgressHUD.h>
#import <AFNetworking.h>

@implementation BaseRequestModel

/**
 Post请求数据(带菊花)
 */
+(void)RequestDatafromView:(UIViewController *)viewcontroller urlStr:(NSString *)urlStr  Parameter:(NSDictionary *)parameter withSuccessBlock:(SuccessBlock)successblock withFailureBlock:(FailureBlock)failureBlock{

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
//    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.requestSerializer.timeoutInterval = 10.0f;
    //设置菊花
//    [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
//    [MBProgressHUDManger HUDHotWheelsWithView:viewcontroller.view];
    
    //发送
    [session POST:[NSString stringWithFormat:@"%@%@",BaseServerURL,urlStr] parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        [UIView animateWithDuration:0.25 animations:^{
            
//            [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];

        } completion:^(BOOL finished) {
//    打印完整URL和详细参数
            NSString *absolute = [self absoluteUrlWithPath:urlStr];
            [self logWithSuccessResponseWithurl:absolute params:parameter];
            
            successblock(responseObject);
            
//            if ([responseObject[@"Code"] intValue]==0||[responseObject[@"Code"] intValue]==1001418||[responseObject[@"Code"] intValue]==1001419)
//            {
//                successblock(responseObject);
//            }
//            else if ([responseObject[@"Code"] intValue]==100004)
//            {//登陆过期
//                [[NSNotificationCenter defaultCenter]postNotificationName:@"loginoverdue" object:nil];
//                [MBProgressHUDManger HUDPromptWithView:viewcontroller.view message:responseObject[@"Msg"]];
//            }
//            else
//            {
//                failureBlock(responseObject);
////                [MBProgressHUDManger HUDPromptWithView:viewcontroller.view message:responseObject[@"Msg"]];
//            }
        }];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //    打印完整URL和详细参数
        NSString *absolute = [self absoluteUrlWithPath:urlStr];
         [self logWithSuccessResponseWithurl:absolute params:parameter];
//        [self logWithFailError:error url:absolute params:parameter];
        NSLog(@"Data request failed =\n%@",error);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
//        [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
//        [MBProgressHUDManger HUDPromptWithView:viewcontroller.view message:@"Data request failed"];
    }];
}


/**
 Post请求数据(不带菊花)
 */
+(void)RequestDataWithoutHUDfromView:(UIViewController *)viewcontroller urlStr:(NSString *)urlStr  Parameter:(NSDictionary *)parameter withSuccessBlock:(SuccessBlock)successblock withFailureBlock:(FailureBlock)failureBlock{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    //    session.requestSerializer = [AFJSONRequestSerializer serializer];
    //  设置加载时间
    session.requestSerializer.timeoutInterval = 10.0f;
   
    //发送
    [session POST:[NSString stringWithFormat:@"%@%@",BaseServerURL,urlStr] parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
        nil;
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        [UIView animateWithDuration:0.25 animations:^{
            
//            [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
            
        } completion:^(BOOL finished) {
            //    打印完整URL和详细参数
            NSString *absolute = [self absoluteUrlWithPath:urlStr];
            [self logWithSuccessResponseWithurl:absolute params:parameter];
            
            if ([responseObject[@"Code"] intValue]==0||[responseObject[@"Code"] intValue]==1001418||[responseObject[@"Code"] intValue]==1001419)
            {
                successblock(responseObject);
            }
//            else if ([responseObject[@"Code"] intValue]==100004)
//            {//登陆过期
//                [[NSNotificationCenter defaultCenter]postNotificationName:@"loginoverdue" object:nil];
//                [MBProgressHUDManger HUDPromptWithView:viewcontroller.view message:responseObject[@"Msg"]];
//            }
            else
            {
                failureBlock(responseObject);
//                [MBProgressHUDManger HUDPromptWithView:viewcontroller.view message:responseObject[@"Msg"]];
            }
        }];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //    打印完整URL和详细参数
        NSString *absolute = [self absoluteUrlWithPath:urlStr];
        [self logWithSuccessResponseWithurl:absolute params:parameter];
        //        [self logWithFailError:error url:absolute params:parameter];
        NSLog(@"Data request failed =\n%@",error);
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
//        [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
//        [MBProgressHUDManger HUDPromptWithView:viewcontroller.view message:@"Data request failed"];
    }];
}
#pragma mark -- 打印完整的URL地址
+ (void)logWithFailError:(NSError *)error url:(NSString *)url params:(id)params {
    NSString *format = @" params: ";
    if (params == nil || ![params isKindOfClass:[NSDictionary class]]) {
        format = @"";
        params = @"";
    }
    
    HYBAppLog(@"\n");
    if ([error code] == NSURLErrorCancelled) {
        HYBAppLog(@"\nRequest was canceled mannully, URL: %@ %@%@\n\n",
                  [self generateGETAbsoluteURL:url params:params],
                  format,
                  params);
    } else {
        HYBAppLog(@"\nRequest error, URL: %@ %@%@\n errorInfos:%@\n\n",
                  [self generateGETAbsoluteURL:url params:params],
                  format,
                  params,
                  [error localizedDescription]);
    }
}





+ (NSString *)absoluteUrlWithPath:(NSString *)path {
    if (path == nil || path.length == 0) {
        return @"";
    }
    if (BaseServerURL == nil || [BaseServerURL length] == 0) {
        return path;
    }
    NSString *absoluteUrl = path;
    if (![path hasPrefix:@"http://"] && ![path hasPrefix:@"https://"]) {
        if ([BaseServerURL hasSuffix:@"/"]) {
            if ([path hasPrefix:@"/"]) {
                NSMutableString * mutablePath = [NSMutableString stringWithString:path];
                [mutablePath deleteCharactersInRange:NSMakeRange(0, 1)];
                absoluteUrl = [NSString stringWithFormat:@"%@%@",
                               BaseServerURL, mutablePath];
            } else {
                absoluteUrl = [NSString stringWithFormat:@"%@%@",BaseServerURL, path];
            }
        } else {
            if ([path hasPrefix:@"/"]) {
                absoluteUrl = [NSString stringWithFormat:@"%@%@",BaseServerURL, path];
            } else {
                absoluteUrl = [NSString stringWithFormat:@"%@/%@",
                               BaseServerURL, path];
            }
        }
    }
    
    return absoluteUrl;
}
+(void)logWithSuccessResponseWithurl:(NSString *)url params:(NSDictionary *)params{
    NSLog(@"\nRequestURL=:\n %@\n params:%@\n",
              [self generateGETAbsoluteURL:url params:params],params);
}


// 仅对一级字典结构起作用
+ (NSString *)generateGETAbsoluteURL:(NSString *)url params:(id)params {
    if (params == nil || ![params isKindOfClass:[NSDictionary class]] || [params count] == 0) {
        return url;
    }
    
    NSString *queries = @"";
    for (NSString *key in params) {
        id value = [params objectForKey:key];
        
        if ([value isKindOfClass:[NSDictionary class]]) {
            continue;
        } else if ([value isKindOfClass:[NSArray class]]) {
            continue;
        } else if ([value isKindOfClass:[NSSet class]]) {
            continue;
        } else {
            queries = [NSString stringWithFormat:@"%@%@=%@&",
                       (queries.length == 0 ? @"&" : queries),
                       key,
                       value];
        }
    }
    
    if (queries.length > 1) {
        queries = [queries substringToIndex:queries.length - 1];
    }
    
    if (([url hasPrefix:@"http://"] || [url hasPrefix:@"https://"]) && queries.length > 1) {
        if ([url rangeOfString:@"?"].location != NSNotFound
            || [url rangeOfString:@"#"].location != NSNotFound) {
            url = [NSString stringWithFormat:@"%@%@", url, queries];
        } else {
            queries = [queries substringFromIndex:1];
            url = [NSString stringWithFormat:@"%@?%@", url, queries];
        }
    }
    
    return url.length == 0 ? queries : url;
}





//多图上传图片
+(void)RequestImageWithViewcontroller:(UIViewController *)viewcontroller urlStr:(NSString *)urlStr Parm:(NSDictionary *)parm imgeDataArry:(NSArray *)imgeDataArry withSuccessBlock:(SuccessBlock)successblock
{
    AFHTTPSessionManager *ma = [AFHTTPSessionManager manager];
    ma.responseSerializer.acceptableContentTypes =[NSSet setWithObject:@"text/html"];
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseServerURL,urlStr];
//
//    [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
//    [MBProgressHUDManger HUDHotWheelsWithView:viewcontroller.view];
    //
    [ma POST:URL parameters:parm constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
       
        for (int i=0; i<imgeDataArry.count; i++) {
            //使用日期生成图片名称
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss:SSS";
            NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
         //将多张图的二进制文件拼在一起(name后面的value一定要跟后台给的接口文档的key一致)
            [formData appendPartWithFileData:imgeDataArry[i] name:@"imge" fileName:fileName mimeType:@"image/jpeg"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"上传结果=%@",responseObject);
//        [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
        successblock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
//        [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
//        [MBProgressHUDManger HUDPromptWithView:viewcontroller.view message:@"图片上传失败"];
        
    }];
}
/**
 修改用户头像
 */

+(void)UpdataUserPhotoWithViewcontroller:(UIViewController *)viewcontroller urlStr:(NSString *)urlStr parm:(NSDictionary *)parm data:(NSData *)data withSuccessBlock:(SuccessBlock)successblock
{
    AFHTTPSessionManager *ma = [AFHTTPSessionManager manager];
    ma.responseSerializer.acceptableContentTypes =[NSSet setWithObject:@"text/html"];
     NSString *URL = [NSString stringWithFormat:@"%@%@",BaseServerURL,urlStr];
    
//    [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
//    [MBProgressHUDManger HUDHotWheelsWithView:viewcontroller.view];
    //
    [ma POST:URL parameters:parm constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"imge" fileName:@"imge.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"图片上传结果=%@",responseObject);
//        [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
        successblock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error=%@",error);
//        [MBProgressHUDManger HUDHiddenWithView:viewcontroller.view];
//        [MBProgressHUDManger HUDPromptWithView:viewcontroller.view message:@"图片上传失败"];
        
    }];
}

//上传视频
+(void)requestVideoWithParm:(NSDictionary *)parm dataurl:(NSString *)dataurl withSuccessBlock:(SuccessBlock)successblock
{
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseServerURL,@"Api/Upload/file.html"];
    
    
    [manager POST:URL parameters:parm constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSError *error;
        
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:dataurl] name:@"uploadname" fileName:@"filename.mp4" mimeType:@"video/mpeg4" error:&error];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"上传中 %@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上传成功");
        
        successblock(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"error=%@",error);
        NSLog(@"上传失败");
        
    }];
    
}














@end
